
PLUG.Platform = PLUG_PLATFORM_SHARED

PLUG.ClassName = "sh_pprotect"
PLUG.PrintName = "GManage Prop Protection"
PLUG.Author = "thomasfn"

function PLUG:Init()

end

function PLUG:AddHooks()
	plugs.Hook( PLUG_PLATFORM_SERVER, "PlayerSpawnedProp" )
	plugs.Hook( PLUG_PLATFORM_SERVER, "PlayerSpawnedNPC" )
	plugs.Hook( PLUG_PLATFORM_SERVER, "PlayerSpawnedSENT" )
	plugs.Hook( PLUG_PLATFORM_SERVER, "PlayerSpawnedVehicle" )
	plugs.Hook( PLUG_PLATFORM_SERVER, "PlayerSpawnedEffect" )
	plugs.Hook( PLUG_PLATFORM_SERVER, "PlayerSpawnedRagdoll" )
	plugs.Hook( PLUG_PLATFORM_SERVER, "CanPlayerUnfreeze" )
	plugs.Hook( PLUG_PLATFORM_SERVER, "CanTool" )
	
	plugs.Hook( PLUG_PLATFORM_SHARED, "PhysgunPickup" )
	
	plugs.Hook( PLUG_PLATFORM_CLIENT, "HUDPaint" )
end

function PLUG:PlayerSpawnedProp( ply, mdl, ent )
	ent:G_SetOwner( ply )
end

function PLUG:PlayerSpawnedRagdoll( ply, mdl, ent )
	ent:G_SetOwner( ply )
end

function PLUG:PlayerSpawnedEffect( ply, mdl, ent )
	ent:G_SetOwner( ply )
end

function PLUG:PlayerSpawnedNPC( ply, ent )
	ent:G_SetOwner( ply )
end

function PLUG:PlayerSpawnedSENT( ply, ent )
	ent:G_SetOwner( ply )
end

function PLUG:PlayerSpawnedVehicle( ply, ent )
	ent:G_SetOwner( ply )
end

function PLUG:CanPlayerUnfreeze( ply, ent, physobj )
	return self:CanAffectObject( ply, ent, "physgun" )
end

function PLUG:CanTool( ply, tr, mode )
	local ent = tr.Entity
	if (ent && ent:IsValid()) then
		return self:CanAffectObject( ply, ent, "toolgun" )
	end
end

function PLUG:PhysgunPickup( ply, ent )
	return self:CanAffectObject( ply, ent, "physgun" )
end

function PLUG:CanAffectObject( ply, ent, priv )
	if (ent:GetClass() == "player") then
		if (CLIENT) then return false end
		if (SERVER) then return ply:HasPriv( priv .. "_players" ) && ply:CanDoActionOn( ent ) end
	end
	local owner = ent:G_GetOwner()
	if (owner && owner:IsValid()) then
		return (owner == ply) || (SERVER && ply:HasPriv( priv .. "_all" ))
	end
	return false
end

local red = Color( 200, 0, 0 )
function PLUG:HUDPaint()
	local tr = LocalPlayer():GetEyeTrace()
	if (tr.Entity && tr.Entity:IsValid()) then
		local owner = tr.Entity:G_GetOwner()
		if (owner && owner:IsValid()) then
			surface.SetFont( "ScoreboardText" )
			local t = "Owned by: " .. owner:Nick()
			local tw, th = surface.GetTextSize( t )
			draw.SimpleText( t, "ScoreboardText", ScrW()-tw, ScrH()-th, red, TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP )
		end
	end
end

function PLUG:EntityExtend( meta )
	if (SERVER) then
		function meta:G_SetOwner( ply )
			self._OWNER = ply
			self:SetNWEntity( "G_Owner", ply )
		end
	end
	function meta:G_GetOwner()
		if (SERVER) then
			return self._OWNER
		end
		if (CLIENT) then
			return self:GetNWEntity( "G_Owner" )
		end
	end
end